import { useMemberStore } from '@/store';
import {
  createRouter,
  createWebHashHistory,
  type RouteRecordRaw,
} from 'vue-router';
const routes: RouteRecordRaw[] = [
  {
    path: '/',
    component: () => import('@/views/Layout/index.vue'),
    children: [
      { path: '/', component: () => import('@/views/Home/index.vue') },
      {
        path: '/category/:id',
        component: () => import('@/views/Category/index.vue'),
      },
      {
        path: '/goods/:id',
        component: () => import('@/views/Goods/index.vue'),
      },
      {
        path: '/cart',
        component: () => import('@/views/Cart/index.vue'),
      },
      {
        path: '/member/checkout',
        component: () => import('@/views/Checkout/index.vue'),
      },
      {
        path: '/member/pay',
        component: () => import('@/views/Pay/index.vue'),
      },
      {
        path: '/member/pay/callback',
        component: () => import('@/views/Pay/callback.vue'),
      },
      {
        path: '/member',
        component: () => import('@/views/Member/Layout/index.vue'),
        children: [
          {
            path: '',
            component: () => import('@/views/Member/Home/index.vue'),
          },
          {
            path: 'order',
            component: () => import('@/views/Member/Order/index.vue'),
          },
        ],
      },
    ],
  },
  {
    path: '/login/callback',
    component: () => import('@/views/Login/callback.vue'),
  },
  {
    path: '/login',
    component: () => import('@/views/Login/index.vue'),
  },
  {
    path: '/text',
    component: () => import('@/views/Text/index.vue'),
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
  scrollBehavior() {
    // 始终滚动到顶部
    return { top: 0, behavior: 'smooth' };
  },
});

router.beforeEach((to) => {
  const member = useMemberStore();
  if (to.path.startsWith('/member') && !member.isLogin) {
    return `/login?target=${to.fullPath}`;
  }
});
export default router;
